package com.jb.repair.acticity;

import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ListView;

import com.jb.repair.R;
import com.jb.repair.adapter.CheckRegisParentAdapter;
import com.jb.repair.dao.ModifyDb;
import com.jb.repair.dao.QueryDb;
import com.jb.repair.model.DeviceModel;
import com.jb.repair.util.MessageUtil;
import com.jb.repair.view.TitleView;

import java.util.ArrayList;
import java.util.List;

/**
 * 批量处理
 * 进入界面后默认展示观察类项目
 * Created by gaobin on 2015/11/19.
 */
public class BatchDealActivity extends BaseActivity implements View.OnClickListener {
    private Button btn_obser, btn_num;
    private static ListView lv_data;
    private TitleView titleView;

    private static CheckRegisParentAdapter mAdapter;
    private static List<DeviceModel> obserList;
    private static List<DeviceModel> numList;
    private String posId;
    private static boolean isNumType = false;
    private QueryDb queryDb;
    private int index_obser = -1;
    private int index_num = -1;
    private static List<String> guidList = new ArrayList<>();
    private int numDevice = 0;//带数值类点检项的设备数目

    private boolean jumpFromTag = false; // 是否通过扫描NFC进来此界面的

    private static final String TAG = "BatchDealActivity";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MessageUtil.dismissProgressDialog();
            switch (msg.what) {
                case 0:
                    mAdapter.notifyDataSetChanged();
                    break;
                case 1:
                    MessageUtil.showToast(getApplicationContext(), "保存成功");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_batch_deal);
        queryDb = QueryDb.getInstance(getApplicationContext());
        posId = getIntent().getStringExtra("posId");
        // 设定，是否是通过扫NFC进入此页面的
        jumpFromTag = getIntent().getBooleanExtra("jumpFromTag", false);
        Log.i(TAG, "是否扫码进入：" + jumpFromTag + "");
        initView();
        obserList = new ArrayList<>();
        numList = new ArrayList<>();


        mAdapter = new CheckRegisParentAdapter(this, obserList, true, jumpFromTag);
        lv_data.setAdapter(mAdapter);
        lv_data.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        // 判断滚动到底部
                        if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
                            if (isNumType) {
                                DeviceModel model = queryDb.getPosDeviceModel(CheckLocActivity.task_id, posId, 2, ++index_num);
                                while (model == null && index_num < numDevice) {
                                    model = queryDb.getPosDeviceModel(CheckLocActivity.task_id, posId, 2, ++index_num);
                                }
                                if (model != null) {
                                    numList.add(model);
                                    mAdapter.notifyDataSetChanged();
                                } else if (index_num >= numDevice) {
                                    MessageUtil.showToast(BatchDealActivity.this, "没有更多数据了");
                                }
                            } else {
                                DeviceModel model = queryDb.getPosDeviceModel(CheckLocActivity.task_id, posId, 1, ++index_obser);
                                while (model == null && index_obser < numDevice) {
                                    model = queryDb.getPosDeviceModel(CheckLocActivity.task_id, posId, 2, ++index_obser);
                                }
                                if (model != null) {
                                    obserList.add(model);
                                    mAdapter.notifyDataSetChanged();
                                } else if (index_obser >= numDevice) {
                                    MessageUtil.showToast(BatchDealActivity.this, "没有更多数据了");
                                }
                            }
                        }
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
        //初始化数据
        MessageUtil.showProgressDialog(BatchDealActivity.this, "正在加载");
        new Thread() {
            @Override
            public void run() {
                super.run();
                int count = 0;//循环次数
                numDevice = queryDb.getDeviceNum(CheckLocActivity.task_id, posId);
                Log.i(TAG, "设备数目为：" + numDevice);
                //初始化观察类数据
                while (obserList.size() < 3 && ++count <= numDevice) {
                    DeviceModel modelObser = queryDb.getPosDeviceModel(CheckLocActivity.task_id, posId, 1, ++index_obser);
                    while (modelObser == null && index_obser < numDevice) {
                        modelObser = queryDb.getPosDeviceModel(CheckLocActivity.task_id, posId, 1, ++index_obser);
                    }
                    if (modelObser != null) {
                        obserList.add(modelObser);
                    }
                }
                count = 0;

                //初始化数值类数据
                while (numList.size() < 3 && ++count <= numDevice) {
                    DeviceModel modelNum = queryDb.getPosDeviceModel(CheckLocActivity.task_id, posId, 2, ++index_num);
                    while (modelNum == null && index_num < numDevice) {
                        modelNum = queryDb.getPosDeviceModel(CheckLocActivity.task_id, posId, 2, ++index_num);
                    }
                    if (modelNum != null) {
                        numList.add(modelNum);
                    }
                }

                handler.sendEmptyMessage(0);
            }
        }.start();


    }

    private void initView() {
        titleView = (TitleView) findViewById(R.id.titleView);
        btn_num = (Button) findViewById(R.id.btn_num);
        btn_obser = (Button) findViewById(R.id.btn_obser);
        lv_data = (ListView) findViewById(R.id.lv_data);
        btn_obser.setOnClickListener(this);
        btn_num.setOnClickListener(this);

        titleView.setTitle(getIntent().getStringExtra("posName"));
        titleView.setOnClickListener(new TitleView.OnTitleViewClickListener() {
            @Override
            public void onRightTextClick(View view) {
                super.onRightTextClick(view);
                MessageUtil.showProgressDialog(BatchDealActivity.this, "正在保存");
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        ModifyDb.getInstance(BatchDealActivity.this).batchCheck(posId, guidList);
                        handler.sendEmptyMessage(1);
                    }
                }.start();
            }

            @Override
            public void onLeftImageClick(View view) {
                super.onLeftImageClick(view);
                finish();
            }
        });

    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_num:
                isNumType = true;
                int version = android.os.Build.VERSION.SDK_INT;
//                Log.i("BatchDealActivity","版本号为："+version);
                if(android.os.Build.VERSION.SDK_INT >= 16) {
                    btn_num.setBackground(ContextCompat.getDrawable(this, R.drawable.textview_selected));
                    btn_obser.setBackground(ContextCompat.getDrawable(this, R.drawable.textview_unselet));
                }else{
                    btn_num.setBackgroundResource(R.drawable.textview_selected);
                    btn_obser.setBackgroundResource(R.drawable.textview_unselet);
                }
                btn_num.setTextColor(getResources().getColor(R.color.white_font));
                btn_obser.setTextColor(getResources().getColor(R.color.main_textcolor));
                mAdapter.notifyDataSetChanged();
                mAdapter = new CheckRegisParentAdapter(BatchDealActivity.this, numList, true, jumpFromTag);

                lv_data.setAdapter(mAdapter);
                break;
            case R.id.btn_obser:
                isNumType = false;
                if(android.os.Build.VERSION.SDK_INT >= 16){
                    btn_obser.setBackground(ContextCompat.getDrawable(this,R.drawable.textview_selected));
                    btn_num.setBackground(ContextCompat.getDrawable(this,R.drawable.textview_unselet));
                }else {
                    btn_obser.setBackgroundResource(R.drawable.textview_selected);
                    btn_num.setBackgroundResource(R.drawable.textview_unselet);

                }

                btn_obser.setTextColor(getResources().getColor(R.color.white_font));
                btn_num.setTextColor(getResources().getColor(R.color.main_textcolor));
                mAdapter.notifyDataSetChanged();
                mAdapter = new CheckRegisParentAdapter(BatchDealActivity.this, obserList, true, jumpFromTag);
                lv_data.setAdapter(mAdapter);
                break;
        }
    }

    public static void update(final int position, final int childPosition, final int cycle, final String result) {
        if ("未检查".endsWith(result) && !isNumType)
            switch (cycle) {
                case 0:
                    guidList.add(obserList.get(position).todayCheckList.get(childPosition).resultId);
                    break;
                case 1:
                    guidList.add(obserList.get(position).weekCheckList.get(childPosition).resultId);
                    break;
                case 2:
                    guidList.add(obserList.get(position).monthCheckList.get(childPosition).resultId);
                    break;
                case 3:
                    guidList.add(obserList.get(position).twiceWeekCheckList.get(childPosition).resultId);
                    break;
                case 4:
                    guidList.add(obserList.get(position).thirdWeekCheckList.get(childPosition).resultId);
                    break;
                case 5:
                    guidList.add(obserList.get(position).twiceMonthCheckList.get(childPosition).resultId);
                    break;
            }
        switch (cycle) {
            case 0:
                if (isNumType)
                    numList.get(position).todayCheckList.get(childPosition).checkResult = result;
                else
                    obserList.get(position).todayCheckList.get(childPosition).checkResult = result;
                break;
            case 1:
                if (isNumType)
                    numList.get(position).weekCheckList.get(childPosition).checkResult = result;
                else
                    obserList.get(position).weekCheckList.get(childPosition).checkResult = result;
                break;
            case 2:
                if (isNumType)
                    numList.get(position).monthCheckList.get(childPosition).checkResult = result;
                else
                    obserList.get(position).monthCheckList.get(childPosition).checkResult = result;
                break;
            case 3:
                if (isNumType)
                    numList.get(position).twiceWeekCheckList.get(childPosition).checkResult = result;
                else
                    obserList.get(position).twiceWeekCheckList.get(childPosition).checkResult = result;
                break;
            case 4:
                if (isNumType)
                    numList.get(position).thirdWeekCheckList.get(childPosition).checkResult = result;
                else
                    obserList.get(position).thirdWeekCheckList.get(childPosition).checkResult = result;
                break;
            case 5:
                if (isNumType)
                    numList.get(position).twiceMonthCheckList.get(childPosition).checkResult = result;
                else
                    obserList.get(position).twiceMonthCheckList.get(childPosition).checkResult = result;
                break;
        }

        mAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MessageUtil.dismissProgressDialog();
        numList = null;
        obserList = null;
        guidList.clear();
    }
}
